/**
 * 角色模块数据操作文件
 */

const { query, queryFirst, pool } = require('./common');

/**
 * 验证名称
 * @param {*} role 要查询的角色对象
 * @returns 
 */
const validName = (role) => queryFirst('SELECT 1 FROM roles WHERE `name` = ?', [role.name]);

/**
 * 添加角色
 * @param {*} role 要添加的角色对象
 * @returns 
 */
const addRole = (role) => query('INSERT INTO roles SET ?', role);

/**
 * 添加角色菜单
 * @param {*} roleId 角色ID
 * @param {*} menuIds 菜单ID
 */
const addMenus = async (roleId, menuIds) => {
    const conn = await pool.getConnection();
    try {
        await conn.beginTransaction();
        await conn.query('DELETE FROM role_menu WHERE role_id = ?', [roleId]);
        menuIds = menuIds.map(item => [roleId, item]);
        if (menuIds.length) {
            await conn.query('INSERT INTO role_menu(role_id,menu_id) VALUES ?', [menuIds]);
        }
        await conn.commit();
    } catch (error) {
        await conn.rollback();
        throw error;
    } finally {
        conn.release();
    }
}

/**
 * 修改角色
 * @param {*} name 
 */
const updateRole = async (name, id) => {
    const conn = await pool.getConnection();
    try {
        const [[result]] = await conn.query('SELECT 1 FROM roles WHERE name = ? AND id <> ?', [name, id]);
        if (result) {
            return 0;
        }
        await conn.query('UPDATE roles SET name = ? WHERE id = ?', [name, id]);
        return 1;
    } catch (error) {
        throw error;
    }
    finally {
        conn.release();
    }
}

/**
 * 删除角色
 * @param {*} id 要删除的角色ID
 * @returns 
 */
const deleteRole = async (id) => {
    const conn = await pool.getConnection();
    try {
        await conn.beginTransaction();
        await conn.query('DELETE FROM role_menu WHERE role_id = ?', [id]);
        await conn.query('DELETE FROM roles WHERE id = ?', [id]);
        await conn.commit();
    }
    catch (error) {
        await conn.rollback();
        throw error;
    }
    finally {
        conn.release();
    }
}


/**
 * 根据角色ID查询是否有教师
 * @param {*} id 
 * @returns 
 */
const hasTeacherByRoleId = (id) => queryFirst(`SELECT 1 FROM teacher_role
WHERE role_id = ?
LIMIT 1`, [id]);

/**
 * 获取角色列表
 * @returns 
 */
const getRoleList = () => query('SELECT * FROM roles');

/**
 * 根据教师ID获取教师角色
 * @param {*} id 教师ID
 * @returns 
 */
const getRolesByTeacherId = id => query('SELECT role_id FROM teacher_role WHERE teacher_id = ?', [id]);

module.exports = {
    validName,
    addRole,
    addMenus,
    deleteRole,
    getRoleList,
    updateRole,
    hasTeacherByRoleId,
    getRolesByTeacherId
}